
o_id = 0
def getObjID(prefix="obj"):
    global o_id
    o_id += 1
    return prefix + str(o_id)

c_num = 0
def getClassName(class_type="class"):
    global c_num
    c_num += 1
    return str(class_type) + str(c_num)

class tag:
    def __init__(self, childs=[]):
        self.children = []
        self.parent = None
        for c in childs:
            self.addChild(c)
        self.tagOpts = {}
        self.addTagOpt("id", getObjID(self.__class__.__name__))

    def getID(self):
        return self.tagOpts["id"]

    def getTagOpts(self):
        txt = ""
        for opt in self.tagOpts:
            txt += " %s=\"%s\" " % (opt,
                                    str(self.tagOpts[opt]).replace("\"", "'"))
        return txt

    def childHTML(self):
        ret = ""
        for c in self.children:
            ret += c.toHTML()
        return ret

    def getClassName(self):
        return self.__class__.__name__

    def toHTML(self):
        tagName = self.getClassName()
        return ("<%s%s>\n" % (tagName, self.getTagOpts()) +
                self.childHTML() + ("\n</%s>" % tagName))

    def loadCSS(self):
        for c in self.children:
            c.loadCSS()
    
    def setParent(self, p):
        self.parent = p

    def setClass(self, c):
        self.addTagOpt("class", c)

    def addChild(self, c):
        if c != self:
            c.setParent(self)
            self.children.append(c)
    
    def findChild(self, objId="", objType=""):
        if self.id == objId or objType == self.__class__.__name__:
            return self
        for c in self.children:
            obj = c.findChild(objId, objType)
            if obj:
                return obj
        return None

    def findRelative(self, objId="", objType=""):
        obj = self
        while obj.parent:
            obj = obj.parent
        return obj.findChild(objId, objType)
        
    def addTagOpt(self, name, val):
        self.tagOpts[name] = val


class root(tag):
    def toHTML(self):
            return ("Content-type: text/html\n\n" + 
                    tag.childHTML(self))

class html(tag):
    def __init__(self, childs=[]):
        tag.__init__(self, childs)

class string(tag):
    def __init__(self, s):
        tag.__init__(self, [])
        self.val = s
    
    def toHTML(self):
        return self.val
        

class head(tag):
    def addCSS(self, css):
        self.addChild(css)

class body(tag):
    def __init__(self, childs=[]):
        tag.__init__(self, childs)

class div(tag):
    pass

class script(tag):
    pass

class css(tag):
    def getClassName(self):
        return "link"

    def __init__(self, src):
        tag.__init__(self, [])
        self.addTagOpt("href", src)
        self.addTagOpt("rel", "stylesheet")
